import grails.util.Metadata
import grame.Log4jGrameUtil
import org.apache.log4j.DailyRollingFileAppender

// 加载外部配置文件，按加载顺序覆盖配置项的值。
grails.config.locations = ["classpath:${appName}-config.properties",
                           "classpath:${appName}-config.groovy",
                           "file:/etc/${appName}/config.properties",
                           "file:/etc/${appName}/config.groovy",
                           "file:${userHome}/.${appName}/config.properties",
                           "file:${userHome}/.${appName}/config.groovy"]

// 从系统properties中获取配置文件路径
if (System.properties["${appName}.config.location"]) {
    grails.config.locations << "file:" + System.properties["${appName}.config.location"]
}

grails.project.groupId = appName // change this to alter the default package name and Maven publishing destination

// GORM shared constraints config
grails.gorm.default.constraints = {
    // 所有字段默认可为空，便于数据库字段升级
    '*' nullable: true
    //字符、数字或下划线开头，点号只能分隔字符或数字，其他内容可由字符、数字、下划线、减号组成，但必须以字符、数字或下划线结束。
    id matches: /^[\w\d_]+(?:(?:[\w\d].[\w\d])?[\w\d_-]+[\w\d_])*/
    // \/:*?"<>|以及控制字符不能作为名称
    name matches: /[^\\\/:*?"<>|\x00-\x1F\x7F]+/
    // 可见字符
    visible matches: /[^\x00-\x1F\x7F]+/
}
// GROM default mapping config
grails.gorm.default.mapping = {
    // 分布式数据同步时，本地库与远程库的UUID应保持一致。因此需要使用assigned，由系统管理.
    id generator: 'assigned'
}

// The ACCEPT header will not be used for content negotiation for user agents containing the following strings (defaults to the 4 major rendering engines)
grails.mime.disable.accept.header.userAgents = ['Gecko', 'WebKit', 'Presto', 'Trident']
grails.mime.types = [ // the first one is the default format
                      all          : '*/*', // 'all' maps to '*' or the first available format in withFormat
                      atom         : 'application/atom+xml',
                      css          : 'text/css',
                      csv          : 'text/csv',
                      form         : 'application/x-www-form-urlencoded',
                      html         : ['text/html', 'application/xhtml+xml'],
                      js           : 'text/javascript',
                      json         : ['application/json', 'text/json'],
                      multipartForm: 'multipart/form-data',
                      rss          : 'application/rss+xml',
                      text         : 'text/plain',
                      hal          : ['application/hal+json', 'application/hal+xml'],
                      xml          : ['text/xml', 'application/xml']
]

// URL Mapping Cache Max Size, defaults to 5000
//grails.urlmapping.cache.maxsize = 1000

// Legacy setting for codec used to encode data with ${}
grails.views.default.codec = "html"

// The default scope for controllers. May be prototype, session or singleton.
// If unspecified, controllers are prototype scoped.
grails.controllers.defaultScope = 'singleton'

// GSP settings
grails {
    views {
        gsp {
            encoding = 'UTF-8'
            htmlcodec = 'xml' // use xml escaping instead of HTML4 escaping
            codecs {
                expression = 'html' // escapes values inside ${}
                scriptlet = 'html' // escapes output from scriptlets in GSPs
                taglib = 'none' // escapes output from taglibs
                staticparts = 'none' // escapes output from static template parts
            }
        }
        // escapes all not-encoded output at final stage of outputting
        // filteringCodecForContentType.'text/html' = 'html'
    }
}


grails.converters.encoding = "UTF-8"
// scaffolding templates configuration
grails.scaffolding.templates.domainSuffix = 'Instance'

// Set to false to use the new Grails 1.2 JSONBuilder in the render method
grails.json.legacy.builder = false
// enabled native2ascii conversion of i18n properties files
grails.enable.native2ascii = true
// packages to include in Spring bean scanning
grails.spring.bean.packages = []
// whether to disable processing of multi part requests
grails.web.disable.multipart = false

// request parameters to mask when logging exceptions
grails.exceptionresolver.params.exclude = ['password', 'pass', 'pin']

// configure auto-caching of queries by default (if false you can cache individual queries with 'cache: true')
grails.hibernate.cache.queries = false

// configure passing transaction's read-only attribute to Hibernate session, queries and criterias
// set "singleSession = false" OSIV mode in hibernate configuration after enabling
grails.hibernate.pass.readonly = false
// configure passing read-only to OSIV session by default, requires "singleSession = false" OSIV mode
grails.hibernate.osiv.readonly = false

environments {
    development {
        grails.logging.jul.usebridge = true
    }
    production {
        grails.logging.jul.usebridge = false
        // TODO: grails.serverURL = "http://www.changeme.com"
    }
}

// log4j configuration
Metadata metaData = Metadata.getCurrent()
def app_log4j_level = metaData.getProperty('app.log4j.level', 'debug')
def app_log4j_hibernate_level = metaData.getProperty('app.log4j.hibernate.level', 'info')

log4j.main = {
    appenders {
        console name: 'stdout', layout: pattern(conversionPattern: '%d{yyyy-MM-dd HH:mm:ss} [%p] %c{2} %m%n')
        appender new DailyRollingFileAppender(name: 'dailyRollingFile', datePattern: "'.'yyyyMMdd", file: "logs/${metaData.getApplicationName()}.log", layout: pattern(conversionPattern: '%d{yyyy-MM-dd HH:mm:ss} [%p] %c{2} %m%n'))
    }

    root { //default config
        error 'stdout', 'dailyRollingFile' // stdout为输出到console
        additivity = true
    }

    error 'org.codehaus.groovy.grails.web.servlet',        // controllers
            'org.codehaus.groovy.grails.web.pages',          // GSP
            'org.codehaus.groovy.grails.web.sitemesh',       // layouts
            'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
            'org.codehaus.groovy.grails.web.mapping',        // URL mapping
            'org.codehaus.groovy.grails.commons',            // core / classloading
            'org.codehaus.groovy.grails.plugins',            // plugins
            'org.codehaus.groovy.grails.orm.hibernate',      // hibernate integration
            'org.springframework',
            'org.hibernate',
            'net.sf.ehcache.hibernate'

    "${app_log4j_level}" 'conf', 'grails.app.controllers',
            'grails.app.domain',
            'grails.app.services',
            'grails.app.filters',
            "${metaData.getApplicationName()}", 'com.springca'

    "${app_log4j_level == 'debug' ? 'info' : app_log4j_level}" 'grails.app.taglib'

    "${app_log4j_hibernate_level}" 'org.hibernate.SQL'
    "${app_log4j_hibernate_level == 'debug' ? 'trace' : app_log4j_hibernate_level}" 'org.hibernate.type.descriptor.sql.BasicBinder'

}

Log4jGrameUtil.init()
